"use strict"

/**
 * AccountConfig the storage for configurations
 * Inspired by the idea in this SO post :
 * 			http://stackoverflow.com/questions/2300356/using-a-single-row-configuration-table-in-sql-server-database-bad-idea
 *
 * TODO: SMTP config, SMS Gateway Config etc...
 */
module.exports = function(sequelize, DataTypes) {
  var _           = require('lodash')
    ,debug        = require('debug')('qywx-api-models')
    ,randomstring = require('randomstring');

  var jwtAlgorithm = [
                        'HS256',  //HMAC using SHA-256 hash algorithm
                        'HS384', 'HS512',
                        'RS512',  //RSASSA using SHA-512 hash algorithm
                        'RS256', 'RS384',
                        'ES256', //ECDSA using P-256 curve and SHA-256 hash algorithm
                        'ES384', 'ES512'
                      ];

  var AccountConfig = sequelize.define("AccountConfig", {
      corpId: {
        type: DataTypes.STRING(128)
        , allowNull: false
        , unique: 'uniqueAccountConfigOfCorpId'
      }
      ,groupName: {
        type: DataTypes.STRING(128)
        , field: 'group_name'
      }
      ,secret: {
        type: DataTypes.STRING(1024)
        ,allowNull: false
      }
      ,jwtAccessTokenSecret: {
        type: DataTypes.STRING(1024)
        ,allowNull: false
        ,field: 'jwt_access_token_secret'
        ,defaultValue: function(){
          return randomstring.generate(64)
        }
      }
      ,jwtAccessTokenExpiresIn: { //Token有效期，单位为毫秒
        type: DataTypes.INTEGER.UNSIGNED
        ,allowNull: false
        ,defaultValue: 7 * 24 * 60 * 60 * 1000  //Default 有效期为7天
        ,field: 'jwt_access_token_expires_in'
      }
      ,jwtAccessTokenAlgorithm: {
        type: DataTypes.ENUM(jwtAlgorithm)
        ,allowNull: false
        ,field: 'jwt_access_token_algorithm'
        ,defaultValue: 'HS512'
      }
      ,singleRowLock: {
        type: DataTypes.INTEGER,
        allowNull: false,
        field: 'single_row_lock',
        defaultValue: 0,
        unique: "uniqueAccountConfigOfCorpId",
        validate: { min: 0, max: 0 }
      }
    }, {
      classMethods: {

      },
      instanceMethods: {

      }
  });

  AccountConfig.jwtAlgorithmEnum = jwtAlgorithm;


  return AccountConfig;
};
